/**    
* @Title: JobLockAspect.java  
* @Package com.kaver.capital.web.aop   
* @author roc   
* @date 2021年1月11日 上午9:55:17  
* @version V1.0  
* @copyright kaver 
*/
package com.kaver.job.core.djob;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.kaver.job.core.biz.model.ReturnT;
import com.kaver.job.core.handler.annotation.Job;
import com.kaver.job.core.handler.annotation.JobLock;
import com.kaver.job.core.util.MD5Util;

/**  
* @ClassName: JobLockAspect  
* @Description: job任务锁
* @author roc  
* @date 2021年1月11日 上午9:55:17  
*    
*/
@Aspect
public class JobLockAspect {
    private Logger logger = LoggerFactory.getLogger(JobLockAspect.class);
    @Autowired
    RedissonClient redissonClient;
    
    @Pointcut("@annotation(com.kaver.job.core.handler.annotation.Job)")
    private void aspect() {}
    
    @Around("aspect()")
    public Object around(JoinPoint joinPoint) throws Throwable {
        String param = (String)joinPoint.getArgs()[0];
        MethodSignature sig = (MethodSignature)joinPoint.getSignature();
        Method method = sig.getMethod();
        Job job = method.getAnnotation(Job.class);
        JobLock jobLock = method.getAnnotation(JobLock.class);
        if (job != null && jobLock != null) {
            if (param == null) {
                param = "";
            }
            String lockKey = "job_" + job.value() + "_" + MD5Util.encrypt(param);
            RLock lock = redissonClient.getLock(lockKey);
            if (lock.tryLock()) {
                try {
                    return ((ProceedingJoinPoint)joinPoint).proceed();
                } finally {
                    lock.unlock();
                }
            } else {
                logger.warn("job：" + job.value() + "获取锁失败" + param);
                return ReturnT.FAIL;
            }
        }
        return ((ProceedingJoinPoint)joinPoint).proceed();
    }
}
